package com.eight.cloud.core.utils.format;

import cn.hutool.core.util.StrUtil;

import java.security.SecureRandom;
import java.util.Base64;

import static com.eight.cloud.core.global.constant.NumConstant.*;

/**
 * 随机字符串工具类
 *
 * @ClassName: RandomStrUtil
 * @Author: TXC
 * @Date: 2024-11-14 16:35
 **/
public class RandomStrUtil {
    /**
     * 获取指定长度的随机字符串
     * @param length 长度
     * @return 随机字符串
     */
    public static String getRandomStr(int length) {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 截取字符串
     * @param str 字符串
     * @param length 长度
     * @return
     */
    public static String truncateString(String str, int length) {
        if (StrUtil.isBlank(str) || str.length() <= length) {
            return str;
        }
        return str.substring(ZERO, length);
    }
}
